package com.jeejio.gerritmanage.util;

import com.jeejio.gerritmanage.config.Constant;
import com.jeejio.gerritmanage.config.IConstant;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

public class InvitationUtil {

    private static char[] mArray = new char[26+26+10];

    private static SecureRandom secureRandom = new SecureRandom();

    static {
        int i, ch;
        for (i = 0, ch = 'A'; i < 26; i++, ch++) {
            mArray[i] = (char)(ch);
        }
        for (ch = '0'; i < (26+10); i++, ch++) {
            mArray[i] = (char)(ch);
        }
        for (ch = 'a'; i < (26+10+26); i++, ch++) {
            mArray[i] = (char)(ch);
        }
    }

    public static void genericCode() throws IOException {
        File file = new File(Constant.APP_CONF.invitationFile);
        if (!file.exists()) {
            file.createNewFile();
        }

        StringBuffer buffer = new StringBuffer();
        int max = 0;
        do {
            max = secureRandom.nextInt(IConstant.MAX_INVITATION_CODE);
        } while (max < 6);
        for (int i = 0; i < max; i++) {
            int idx = secureRandom.nextInt(26 + 26 + 10);
            buffer.append(mArray[idx]);
        }

        try (FileOutputStream out = new FileOutputStream(file)) {
            out.getChannel().truncate(0);
            out.write(buffer.toString().getBytes(StandardCharsets.UTF_8));
        }
    }

    public static String getCode() throws IOException {
        char[] buf = new char[IConstant.MAX_INVITATION_CODE];
        File file = new File(Constant.APP_CONF.invitationFile);
        if (!file.exists()) {
            return null;
        }

        try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file))) {
            int readLen = reader.read(buf);
            return new String(buf, 0, readLen);
        }
    }
}
